package org.benjamin.lending.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.benjamin.lending.service.TransactService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class TransactFactoryBean extends AbstractFactoryBean<TransactService> implements ApplicationContextAware {
	
	private ApplicationContext applicationContext;
	
	private String transactName;

	@Override
	protected TransactService createInstance() throws Exception {
		TransactService transactService = null;
		if(StringUtils.isNotBlank(this.transactName)) {
			transactService = this.applicationContext.getBean(this.transactName+"TransactService",TransactService.class);
		}else {
			String[] transactNames = {"sumapay","default"};
			for(String transactName : transactNames) {
				try {
					transactService = this.applicationContext.getBean(transactName+"TransactService",TransactService.class);
					logger.info("成功注册交易服务类"+transactName);
					return transactService;
				}catch(NoSuchBeanDefinitionException e) {
					logger.debug("当前交易服务类实现厂商:"+transactName+"未注册");
				}		
			}
		}
		return transactService;
	}

	@Override
	public Class<?> getObjectType() {
		return TransactService.class;
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

}
